package com.github.sub.inter;

import com.github.Commander;
import com.github.Common;

import java.io.File;
import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;

import static com.github.MyAutoTestContext.*;

public class ExeCommander extends Common implements Commander {
    @Override
    public Object run(Map<String, String> command) {
        String eValue = command.get("-e");
        String pValue = command.get("-pa");
        String userName = command.get("-u");

        String read = read(new File(alias + File.separator + eValue));

        String domain = read(new File(interfaceName + File.separator + read.hashCode()));
        String methodName = read(new File(method + File.separator + domain.hashCode()));
        String headerName = read(new File(header + File.separator + domain.hashCode()));
        String current = read(new File(currentPath() + File.separator + PATH + CURRENT_PATH + File.separator + "current"));
        String paramvalue = read(new File(param + File.separator + pValue));

        //header 可以是多个
        String[] split = headerName.split("\n");
        String[] curls = new String[(6 + split.length * 2)];
        if (!isEmpty(userName)) {
            curls = new String[(8 + split.length * 2)];
        }
        curls[0] = "curl";
        curls[1] = current.split("=")[1] + domain;
        curls[2] = "-X";
        curls[3] = methodName;
        curls[4] = "-d";
        curls[5] = paramvalue.replace("\"", "\\\"");
        int index = 6;
        for (String s : split) {
            curls[index++] = "-H";
            curls[index++] = s;
        }
        if (!isEmpty(userName)) {
            File apply = userPath.apply(userName);
            String read1 = read(apply);
            curls[index++] = "-H";
            curls[index++] = "token:" + read1;
        }


        Arrays.stream(curls).collect(Collectors.toList()).forEach(h -> System.out.print(h + DBLANK));
        System.out.println();
        System.out.println("response:");
        String responseString = execCurl(curls);
        String responsePath = response + domain.hashCode() + File.separator;
        File file1 = new File(responsePath);
        if (!file1.exists()) {
            file1.mkdirs();
        }
        String fileName = pValue + "-" + System.nanoTime();
        tradition.outPutFile((paramvalue + "\n" + responseString).getBytes(), responsePath, fileName);
        return responseString;
    }
}